/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2015年10月21日 上午10:38:03
 */
package xj.toolkit.rpc.assemble;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

import xj.toolkit.rpc.RpcService;
import xj.toolkit.rpc.naming.RpcServerNamingService;

/**
 * 解析spring bean，发现rpc service进行组装。
 * 
 * @author <a href="mailto:caoxiaojian@wasu.cn">xiaojiancao</a>
 *
 */
@Service("rpcServiceParser")
public class RpcServiceParser implements BeanPostProcessor {

	private static final Logger logger = LoggerFactory.getLogger(RpcServiceParser.class);

	@Autowired
	private RpcServiceManager rpcServiceManager = null;

	@Autowired
	private RpcServerNamingService namingService = null;

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * bean初始化之后，检查bean是不是rpcservice，如果是的话，解析。
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

		RpcService rpcService = bean.getClass().getAnnotation(RpcService.class);
		if (rpcService == null) {
			return bean;
		}

		if (rpcServiceManager.checkExistRpcService(rpcService.name())) {
			logger.error("Exist service[{}].", rpcService.name());
			throw new BeanInitializationException("Exist service[" + rpcService.name() + "].");
		}

		RpcServiceDescriptor rpcServiceDescriptor = new RpcServiceDescriptor();
		rpcServiceDescriptor.setBeanName(beanName);
		rpcServiceDescriptor.setDescription(rpcService.description());
		rpcServiceDescriptor.setServiceName(rpcService.name());
		rpcServiceDescriptor.setBeanInstance(bean);

		logger.debug("Rpc service[" + rpcService + "].");

		rpcServiceManager.addRpcServiceDescriptor(rpcServiceDescriptor);
		namingService.registerService(rpcService);

		return bean;
	}

}
